/*   
 * Copyright 2009-2010 Rob Schoening
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.beaconframework.util.xml;

import java.util.ArrayList;
import java.util.List;

import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathFunctionResolver;

import org.beaconframework.util.exception.BeaconException;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XPathUtil {
    org.slf4j.Logger log = LoggerFactory.getLogger(XPathUtil.class);
    XPath xpath;

    public XPathUtil() {
        XPathFactory factory = XPathFactory.newInstance();

        xpath = factory.newXPath();
    }

    public XPathUtil(XPath xp) {
        xpath = xp;
    }

    public XPathUtil(NamespaceContext ctx) {
        this();
        xpath.setNamespaceContext(ctx);
    }

    public void setNamespaceContext(NamespaceContext ctx) {
        xpath.setNamespaceContext(ctx);
    }

    public void setXPathFunctionResolver(XPathFunctionResolver resolver) {
        xpath.setXPathFunctionResolver(resolver);
    }

    public String escape(String s) {
        return s;
    }

    public Object eval(Node n, String ex, QName q) {
        try {

            XPathExpression expr = xpath.compile(ex);
            return expr.evaluate(n, q);
        } catch (XPathExpressionException e) {
            throw new BeaconException(e);
        }
    }

    public boolean evalBoolean(Node n, String ex) {

        Boolean b = (Boolean) eval(n, ex, XPathConstants.BOOLEAN);
        if (b != null && b == true) {
            return true;
        } else {
            return false;
        }
    }

    public Element evalElement(Node n, String ex) {
        try {
            return (Element) evalNode(n, ex);
        } catch (ClassCastException e) {
            throw new ClassCastException("Node " + n + " is not an Element");
        }
    }

    public Node evalNode(Node n, String ex) {

        return (Node) eval(n, ex, XPathConstants.NODE);
    }

    public NodeList evalNodeList(Node n, String ex) {

        return (NodeList) eval(n, ex, XPathConstants.NODESET);
    }

    public String evalString(Node n, String ex) {

        String s = (String) eval(n, ex, XPathConstants.STRING);
        log.debug("{} => '{}'", ex, s);
        return s;
    }

    public List<String> evalStringList(Node n, String ex) {
        List<String> tmp = new ArrayList<String>();

        NodeList nl = (NodeList) eval(n, ex, XPathConstants.NODESET);
        for (int i = 0; i < nl.getLength(); i++) {
            Node cn = nl.item(i);
            if (cn.getNodeType() == Node.CDATA_SECTION_NODE
                    || cn.getNodeType() == Node.TEXT_NODE) {
                tmp.add(cn.getNodeValue());
            } else if (cn.getNodeType() == Node.ELEMENT_NODE
                    || cn.getNodeType() == Node.ATTRIBUTE_NODE) {
                tmp.add(cn.getNodeName());
            }

        }
        return tmp;
    }

    public XPath getXPath() {

        return xpath;

    }
}
